"use client"

import { useEffect, useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"
import { BookOpen, CheckCircle, Clock } from "lucide-react"
import {
  BarChart,
  Bar,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
} from "recharts"

// 模拟API接口
interface ContentAnalyticsData {
  contentMatchRate: number
  recognizedText: string[]
  keyTopics: {
    topic: string
    inSyllabus: boolean
  }[]
  contentPace: {
    value: number
    status: "fast" | "normal" | "slow"
  }
  timeSpent: {
    topic: string
    minutes: number
  }[]
  keywordCloud: {
    word: string
    weight: number
  }[]
}

interface ContentAnalyticsProps {
  isActive: boolean
}

// 颜色配置
const COLORS = ["#0088FE", "#00C49F", "#FFBB28", "#FF8042", "#8884d8", "#82ca9d", "#ffc658"]

export function ContentAnalytics({ isActive }: ContentAnalyticsProps) {
  const [data, setData] = useState<ContentAnalyticsData | null>(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (!isActive) {
      return
    }

    setLoading(true)

    // 模拟API调用
    const fetchData = () => {
      // 在实际应用中，这里会调用后端API获取实时分析数据
      const mockData: ContentAnalyticsData = {
        contentMatchRate: 92.5,
        recognizedText: ["微分方程的基本概念", "一阶微分方程的求解方法", "可分离变量的微分方程", "线性微分方程"],
        keyTopics: [
          { topic: "微分方程的基本概念", inSyllabus: true },
          { topic: "一阶微分方程的求解方法", inSyllabus: true },
          { topic: "可分离变量的微分方程", inSyllabus: true },
          { topic: "线性微分方程", inSyllabus: true },
          { topic: "伯努利方程", inSyllabus: false },
        ],
        contentPace: {
          value: 65,
          status: "normal",
        },
        timeSpent: [
          { topic: "微分方程的基本概念", minutes: 12 },
          { topic: "一阶微分方程的求解方法", minutes: 18 },
          { topic: "可分离变量的微分方程", minutes: 15 },
          { topic: "线性微分方程", minutes: 10 },
        ],
        keywordCloud: [
          { word: "微分方程", weight: 10 },
          { word: "一阶微分方程", weight: 8 },
          { word: "可分离变量", weight: 7 },
          { word: "线性微分方程", weight: 9 },
          { word: "常微分方程", weight: 6 },
          { word: "通解", weight: 5 },
          { word: "特解", weight: 5 },
          { word: "初值问题", weight: 7 },
          { word: "边值问题", weight: 6 },
          { word: "欧拉方法", weight: 4 },
          { word: "龙格库塔方法", weight: 3 },
          { word: "伯努利方程", weight: 5 },
        ],
      }

      setData(mockData)
      setLoading(false)
    }

    // 立即获取一次数据
    fetchData()

    // 设置定时器，模拟实时更新
    const intervalId = setInterval(() => {
      if (isActive) {
        fetchData()
      }
    }, 5000)

    return () => {
      clearInterval(intervalId)
    }
  }, [isActive])

  if (!isActive) {
    return <div className="p-8 text-center text-muted-foreground">请点击"开始监控"按钮启动教学内容分析</div>
  }

  if (loading && !data) {
    return <div className="p-8 text-center text-muted-foreground">正在加载内容分析数据...</div>
  }

  if (!data) {
    return <div className="p-8 text-center text-muted-foreground">无法获取内容分析数据</div>
  }

  // 准备时间分配数据
  const timeSpentData = data.timeSpent.map((item) => ({
    name: item.topic,
    value: item.minutes,
  }))

  // 准备关键词云数据
  const keywordData = data.keywordCloud.map((item) => ({
    name: item.word,
    value: item.weight,
  }))

  return (
    <div className="grid gap-6 mt-6">
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">内容匹配度</CardTitle>
            <CheckCircle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{data.contentMatchRate.toFixed(1)}%</div>
            <p className="text-xs text-muted-foreground">与教学大纲的匹配程度</p>
            <Progress className="mt-2" value={data.contentMatchRate} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">教学节奏</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold capitalize">
              {data.contentPace.status === "normal" ? "适中" : data.contentPace.status === "fast" ? "偏快" : "偏慢"}
            </div>
            <p className="text-xs text-muted-foreground">基于内容覆盖速度的评估</p>
            <Progress className="mt-2" value={data.contentPace.value} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">教学大纲符合度</CardTitle>
            <BookOpen className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {data.keyTopics.filter((t) => t.inSyllabus).length}/{data.keyTopics.length}
            </div>
            <p className="text-xs text-muted-foreground">关键主题在教学大纲中的覆盖率</p>
            <Progress
              className="mt-2"
              value={(data.keyTopics.filter((t) => t.inSyllabus).length / data.keyTopics.length) * 100}
            />
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>识别到的内容</CardTitle>
            <CardDescription>通过OCR识别的黑板/PPT内容</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {data.recognizedText.map((text, index) => (
                <div key={index} className="p-2 bg-muted rounded-md text-sm">
                  {text}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>主题时间分配</CardTitle>
            <CardDescription>各主题讲解所用时间</CardDescription>
          </CardHeader>
          <CardContent className="h-[200px]">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={timeSpentData}
                layout="vertical"
                margin={{
                  top: 5,
                  right: 30,
                  left: 20,
                  bottom: 5,
                }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis type="number" />
                <YAxis dataKey="name" type="category" width={150} />
                <Tooltip formatter={(value) => [`${value} 分钟`, "讲解时间"]} />
                <Legend />
                <Bar
                  dataKey="value"
                  name="讲解时间"
                  fill="#8884d8"
                  animationBegin={0}
                  animationDuration={1500}
                  animationEasing="ease-out"
                >
                  {timeSpentData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
        <Card className="md:col-span-2">
          <CardHeader>
            <CardTitle>关键词云</CardTitle>
            <CardDescription>从教学内容中提取的关键词</CardDescription>
          </CardHeader>
          <CardContent className="h-[300px]">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={keywordData}
                  cx="50%"
                  cy="50%"
                  outerRadius={120}
                  innerRadius={60}
                  fill="#8884d8"
                  dataKey="value"
                  nameKey="name"
                  label={(entry) => entry.name}
                  labelLine={true}
                  animationBegin={0}
                  animationDuration={1500}
                  animationEasing="ease-out"
                >
                  {keywordData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip formatter={(value) => [`权重: ${value}`]} />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
